package com.br.egaragens.activitys;

import java.util.List;


import com.br.egaragens.R;
import com.br.egaragens.adaptadores.UsuarioAdaptador;
import com.br.egaragens.controles.UsuarioController;
import com.br.egaragens.entidades.Usuario;
import com.br.egaragens.interfaces.IEntidade;
import com.br.egaragens.util.Util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class LoginUser extends Activity{

	private EditText edtSenha;
	private Button btnLogar;
	private Spinner userSpinner;
	private Usuario usuarioAtual;
	private UsuarioController usuarioController;
	List<Usuario> luser;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_usuario);

		usuarioController = new UsuarioController(getBaseContext());
		btnLogar =(Button) findViewById(R.id.Login_btnLogar);
		edtSenha =(EditText) findViewById(R.id.login_edt_senha);
		userSpinner = (Spinner) findViewById(R.id.login_spinner_user);
		userSpinner.setPrompt("Selecione");

		luser =(List<Usuario>) usuarioController.getAll();
		userSpinner.setAdapter(new UsuarioAdaptador(getBaseContext(), luser));

		btnLogar.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(120);
				verificaLogin();

			}
		});

		userSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View view,int position, long id) {
				usuarioAtual = (Usuario) userSpinner.getAdapter().getItem(position);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});


	};

	public void verificaLogin(){

		if(usuarioAtual.getSenha().toString().equals(edtSenha.getText().toString())){
			Util.usuario = usuarioAtual;
			irParaTelaPrincipal();
		}else{
			senhaInvalida();
		}

	}

	public void senhaInvalida(){
		AlertDialog.Builder alBuilder = new AlertDialog.Builder(LoginUser.this);
		alBuilder.setTitle("Aten��o!");
		alBuilder.setMessage("Senha digita n�o confere!");
		alBuilder.setPositiveButton(" OK ", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

			}
		});
		alBuilder.show();

	}
	public void irParaTelaPrincipal(){
		finish();
		Intent i = new Intent(this, ActivityMain.class);
		i.putExtra("usuario", usuarioAtual);
		startActivity(i);
	}
}
